<template>
  <div>
    <h2>用户管理</h2>
    <!-- 搜索栏 -->
    <div class="search-bar">
      <input
          type="text"
          v-model="searchUsername"
          placeholder="输入用户名"
      />
      <input
          type="text"
          v-model="searchPhone"
          placeholder="输入电话号码"
      />
      <button @click="searchUsers">Search</button>
    </div>

    <!-- 用户表格 -->
    <table>
      <thead>
      <tr>
        <th>用户ID</th>
        <th>用户名</th>
        <th>邮箱</th>
        <th>电话号码</th>
        <th>注册时间</th>
      </tr>
      </thead>
      <tbody>
      <tr v-for="user in users" :key="user.userId">
        <td>{{ user.userId }}</td>
        <td>{{ user.username }}</td>
        <td>{{ user.email }}</td>
        <td>{{ user.phone }}</td>
        <td>{{ user.registrationDate }}</td>

      </tr>
      </tbody>
    </table>

    <!-- 分页组件 -->
    <pagination
        :current-page="currentPageNumber"
        :total="totalUsers"
        :page-size="pageSize"
        @update:currentPage="handlePageChange"
    />
  </div>
</template>

<script>
import { ref } from 'vue';
import Pagination from '@/components/Pagination.vue';
import axios from 'axios';

export default {
  components: {
    Pagination,
  },
  props: {
    currentPageNumber: {
      type: Number,
      required: true,
    },
    pageSize: {
      type: Number,
      required: true,
    },
  },
  setup(props, { emit }) {
    const users = ref([]);
    const totalUsers = ref(0);
    const searchUsername = ref('');
    const searchPhone = ref('');

    // 请求用户数据
    const fetchUsers = async (pageNum, pageSize, username = '', phone = '') => {
      try {
        const response = await axios.post('admins/findUsers', {
          pageNum,
          pageSize,
          username,
          phone,
        });

        users.value = response.data.records;
        totalUsers.value = response.data.total;
      } catch (error) {
        console.error('Failed to fetch users:', error);
      }
    };

    // 搜索用户
    const searchUsers = () => {
      fetchUsers(props.currentPageNumber, props.pageSize, searchUsername.value, searchPhone.value);
    };

    // 处理分页更改
    const handlePageChange = (newPage) => {
      emit('update:currentPageNumber', newPage);
      fetchUsers(newPage, props.pageSize, searchUsername.value, searchPhone.value);
    };

    // 初始化时加载用户数据
    fetchUsers(props.currentPageNumber, props.pageSize);

    return {
      users,
      totalUsers,
      searchUsername,
      searchPhone,
      searchUsers,
      handlePageChange,
    };
  },
};
</script>

<style scoped>
/* 样式 */
table {
  width: 100%;
  border-collapse: collapse;
  margin-top: 20px;
}

table th,
table td {
  border: 1px solid #ccc;
  padding: 10px;
  text-align: left;
}

.search-bar {
  display: flex;
  gap: 10px;
  margin-bottom: 20px;
}
</style>
